#coding:utf-8


import pickle
import logging
import sys, os
import datetime, time

now = datetime.datetime.now

class _BaseReport:
    def __init__(self, name, path):
        self._log = logging.getLogger(name)
        path = os.path.join(os.getcwd(), path)
        if not os.path.isdir(path):
            os.mkdir(path)
        self._path = path
        
        self._current = None
        self._current_hdlr = None
        

#日志端
class DataReport(_BaseReport):
    def __init__(self):
        _BaseReport.__init__(self, 'data', 'log')
        
    def checkTime(self):
        now = time.strftime("%m%d%H")
        if now != self._current:
            year_start = datetime.date(2009, 1, 1)
            now_day = datetime.date.today()
            fullName = os.path.join(self._path, '%s.log'%(str((now_day - year_start).days) + time.strftime("%H")))
            hdlr = logging.FileHandler(fullName)
        
            formatter = logging.Formatter("%(asctime)s%(message)s", datefmt = "(%Y-%m-%d %H:%M:%S)") 
            hdlr.setFormatter(formatter)
        
            self._log.addHandler(hdlr)
            if self._current_hdlr is not None:
                self._log.removeHandler(self._current_hdlr)
            self._log.setLevel(logging.DEBUG)
            self._current = now
            self._current_hdlr = hdlr
            
    def log(self, msg):
        self.checkTime()
        self._log.info(msg)
        
_dataReport = DataReport()
log = _dataReport.log

#事件端
class EventReport(_BaseReport):
    def __init__(self):
        _BaseReport.__init__(self, 'event', 'event')
        
    def checkTime(self):
        now = time.strftime("%Y%m%d")
        if now != self._current:
            fullName = os.path.join(self._path, '%s.log'%now)
            hdlr = logging.FileHandler(fullName)
        
            formatter = logging.Formatter("%(asctime)s%(message)s", datefmt = "(%Y-%m-%d %H:%M:%S)") 
            hdlr.setFormatter(formatter)
        
            self._log.addHandler(hdlr)
            if self._current_hdlr is not None:
                self._log.removeHandler(self._current_hdlr)
            self._log.setLevel(logging.DEBUG)
            self._current_hdlr = hdlr
            self._current = now
        
    def info(self, msg):
        if isinstance(msg ,unicode):
            msg = msg.encode('utf-8')
        self.checkTime()
        self._log.info(msg)
        
    def error(self, msg):
        if isinstance(msg ,unicode):
            msg = msg.encode('utf-8')
        self.checkTime()
        self._log.error(msg)
        
_eventReport = EventReport()
info = _eventReport.info
error = _eventReport.error